import axios from 'axios';
import {Message} from 'element-ui';
import qs from "qs";
import {urls} from './urls';
import {format} from './format';
import Base64 from '@/publicMethod/byBase64';
import {localUitl} from "../utils/localUitl";

let base = new Base64();

const service = axios.create({
  timeout: 30000,
  withCredentials: false, // 是否允许带cookie这些
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  }
})


// 添加请求拦截器
service.interceptors.request.use(
  config => {
    console.log("request", config);
    if (config.url.indexOf("pwdLogin") == -1 &&
      config.url.indexOf("leftMenu") == -1 &&
      config.headers.sendKey != "getUserN" &&
      config.headers.sendKey != "getClients" &&
      config.headers.sendKey != "getActivilys"
    ) {
      config.headers["access_token"] = localUitl.getToken();
    }
    return config;
  },
  error => {
    return Promise.reject(error.data.error.message);
  }
);

//返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  res => {
    console.log("response", res);
    let sendKey = res.config.headers.sendKey;
    //TODO 看是否需要格式化逻辑处理
    if (format[sendKey]) {
      return format[sendKey](res);
    } else {
      return res;
    }
  },
  error => {
    return Promise.reject(error);
  }
);

export const https = {};
for (let [method, mapObj] of urls) {
  if (!https[method]) {
    https[method] = {};
  }
  for (let [key, url] of mapObj) {
    https[method][key] = function (params) {
      const config = {
        method: method,
        url: url,
        params: null,
        headers: {
          sendKey: key
        },
        data: null
        // baseURL: host
      }
      switch (method) {
        case "get":
          if (config.url.indexOf("./static") != -1) {
            config.baseURL = "./";
          }
          config.params = params;
          break;
        case "post":
          let obj = {...params};
          config.data = qs.stringify(obj);
          break;
      }
      return service(config);
    }
  }
}




